<?php
/**
 * Created by PhpStorm.
 * User: sunzexin
 * Date: 2017/12/21
 * Time: 09:36
 */

namespace App\Http\Logics\MiniProgram;

use App\Cafe;
use App\CashCoupon;
use App\City;
use App\Dynamic;
use App\DynamicComment;
use App\Mark;
use App\Menu;
use App\Partner;
use App\Party;
use App\PartySignUp;
use App\Role;
use App\UserFollowCity;
use App\UserFollowMark;
use App\UserFormId;
use App\UserMappingCashCoupon;
use App\UserMappingRole;
use App\UserPraiseDynamic;
use App\Users;
use App\UserFollowCafe;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use App\Http\Logics\BaseLogic;
class UserLogic extends BaseLogic
{
    /**
     * 小程序登录
     * @param $code
     * @return mixed
     */
    public static function login($data)
    {
        try {
            // 通过合作者key获取到合作者ID
            $response = self::getPartnerIdByKey($data['key']);
            if ($response->code) {
                return self::response($response->code);
            }
            $partner_id = $response->data;

            // 从数据库中找到该合作者
            $response = PartnerLogic::getAppidByPartnerId($partner_id);
            if ($response->code) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $partner = $response->data;

            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $partner->appid . "&secret=" . $partner->secret . "&js_code=" . $data['code'] . "&grant_type=authorization_code";

            $response = self::httpGet($url);

            $res = json_decode($response->data);

            // 用户的openid
            $openid = $res->openid;

            // 通过openid获取用户信息
            $response = self::getUserByOpenid($openid);

            // 获取用户信息失败,数据库中不存在该用户
            if ($response->code) {
                $data['wx_app_openid'] = $openid;
                $data['partner_id'] = $partner_id;
                // 对该用户进行注册
                $response = self::register($data);
                if ($response->code) {
                    // 注册失败
                    return self::response($response->code);
                }
            } else {
                // 用户存在则则更新用户信息
                $user = Users::where('wx_app_openid', $openid)->first();
                $user->nickname = $data['nick_name'];
                $user->sex = $data['gender'];
                $user->language = $data['language'];
                $user->province = $data['province'];
                $user->country = $data['country'];
                $user->city = $data['city'];
                // 将头像暂存到服务器
                $avatar_url = downloadImage($data['avatar_url']);
                // 将暂存到本地的头像上传到云存储
                $user->headimgurl = uploadImage($avatar_url, 'avatar');
                // 移除暂存到服务器的图片
                removeImage($avatar_url);
                if (!$user->save()) {
                    // 更新失败
                    return self::response(self::ACCOUNT_REGIST_FAILD);
                }
            }

            $loginSession = str_random(128);
            if (!Redis::set($loginSession, $openid)) {
                // 登录失败
                return self::response(self::LOGIN_ERROR);
            }

            // 将登陆用户的所有权限缓存到Redis中
            $data_second = [
                'loginSession' => $loginSession
            ];
            $response = MenuLogic::getAdminRouteList($data_second);

            if ($response->code){
                return self::response($response->code);
            }

            $route = $response->data;
            if (!Redis::set($loginSession.'route', json_encode($route))) {
                // 登录失败
                return self::response(self::LOGIN_ERROR);
            }
            // 登录成功
            return self::response(self::SUCCESS, $loginSession);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }


    /**
     * 用户注册
     * @param $data 用户信息
     * @return mixed 用户实例信息
     */
    public static function register($data)
    {
        try {
            $user = new Users();
            $user->wx_app_openid = $data['wx_app_openid'];
            $user->nickname = $data['nick_name'];
            $user->sex = $data['gender'];
            $user->language = $data['language'];
            $user->province = $data['province'];
            $user->country = $data['country'];
            $user->city = $data['city'];
            // 将头像暂存到服务器
            $avatar_url = downloadImage($data['avatar_url']);
            // 将暂存到本地的头像上传到云存储
            $user->headimgurl = uploadImage($avatar_url, 'avatar');
            // 移除暂存到服务器的图片
            removeImage($avatar_url);
            $user->partner_id = $data['partner_id'];
            if (!$user->save()) {
                // 注册失败
                return self::response(self::ACCOUNT_REGIST_FAILD);
            }
            // 注册成功
            return self::response(self::SUCCESS, $user);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 用户对咖啡馆添加喜欢动作
     * @param $data 参数（用户loginSession|咖啡馆ID|用户现在是否喜欢咖啡馆状态）
     * @return mixed 返回添加结果
     * @throws \Exception
     */
    public static function followCafe($data)
    {
        try {
            $wx_app_id = Redis::get($data['loginSession']);

            // 通过wx_app_id获取到用户数据
            $response = self::getUserByOpenid($wx_app_id);

            if ($response->code) {
                return self::response(self::ACCOUNT_OR_PASSWORD_IS_WRONG);
            }

            $user = $response->data;

            $user_id = $user->id;

            $cafe_id = $data['cafe_id'];


            if ($data['is_follow']) {
                $user_follow_cafe = UserFollowCafe::where('user_id', $user_id)->where('cafe_id', $cafe_id)->first();
                if (!empty($user_follow_cafe)){
                    return self::response(self::USER_FOLLOW_CAFE_AGAIN);
                }
                $user_follow_cafe = new UserFollowCafe();
                $user_follow_cafe->cafe_id = $cafe_id;
                $user_follow_cafe->user_id = $user_id;
                if (!$user_follow_cafe->save()) {
                    return self::response(self::USER_FOLLOW_CAFE_FAILD);
                }
            } else {
                $user_follow_cafe = UserFollowCafe::where('user_id', $user_id)->where('cafe_id', $cafe_id)->first();
                if (!$user_follow_cafe->delete()) {
                    return self::response(self::OBJECT_DELETE_FAILD);
                }
            }

            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 用户对城市添加喜欢动作
     * @param $data 参数（用户loginSession|咖啡馆ID|用户现在是否喜欢咖啡馆状态）
     * @return mixed 返回添加结果
     * @throws \Exception
     */
    public static function followCity($data)
    {
//        try {
            $wx_app_id = Redis::get($data['loginSession']);

            // 通过wx_app_id获取到用户数据
            $response = self::getUserByOpenid($wx_app_id);

            if ($response->code) {
                return self::response(self::ACCOUNT_OR_PASSWORD_IS_WRONG);
            }

            $user = $response->data;

            $user_id = $user->id;

            $city_id = $data['city_id'];


            if ($data['is_follow']) {
                $user_follow_city = UserFollowCity::where('user_id', $user_id)->where('city_id', $city_id)->first();
                if (!empty($user_follow_city)){
                    return self::response(self::USER_FOLLOW_CITY_AGAIN);
                }
                $user_follow_city = new UserFollowCity();
                $user_follow_city->city_id = $city_id;
                $user_follow_city->user_id = $user_id;
                if (!$user_follow_city->save()) {
                    return self::response(self::USER_FOLLOW_CITY_FAILD);
                }
            } else {
                $user_follow_city = UserFollowCity::where('user_id', $user_id)->where('city_id', $city_id)->first();
                if (!$user_follow_city->delete()) {
                    return self::response(self::OBJECT_DELETE_FAILD);
                }
            }

            return self::response(self::SUCCESS);
//        }catch (\Exception $e){
//            return self::response(self::SYSTEM_ERROR);
//        }
    }

    /**
     * 用户对咖啡馆添加喜欢动作
     * @param $data 参数（用户loginSession|咖啡馆ID|用户现在是否喜欢咖啡馆状态）
     * @return mixed 返回添加结果
     * @throws \Exception
     */
    public static function followMark($data)
    {
        try {
            $wx_app_id = Redis::get($data['loginSession']);

            // 通过wx_app_id获取到用户数据
            $response = self::getUserByOpenid($wx_app_id);

            if ($response->code) {
                return self::response(self::ACCOUNT_OR_PASSWORD_IS_WRONG);
            }
            $user = $response->data;
            $user_id = $user->id;

            if ($data['is_follow']) {
                $user_follow_mark = UserFollowMark::where('user_id', $user_id)->where('mark_id', $data['mark_id'])->first();
                if (!empty($user_follow_mark)){
                    return self::response(self::USER_FOLLOW_MARK_AGAIN);
                }
                $user_follow_mark = new UserFollowMark();
                $user_follow_mark->mark_id = $data['mark_id'];
                $user_follow_mark->user_id = $user_id;
                if (!$user_follow_mark->save()) {
                    return self::response(self::USER_FOLLOW_MARK_FAILD);
                }
            } else {
                $user_follow_mark = UserFollowMark::where('user_id', $user_id)->where('mark_id', $data['mark_id'])->first();
                if (!$user_follow_mark->delete()) {
                    return self::response(self::OBJECT_DELETE_FAILD);
                }
            }

            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取用户数据
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getUserInfo($data)
    {
        try {
            $user = Users::where(function ($query) use ($data) {
                if (!empty($data['wx_app_openid'])) {
                    $query->where('wx_app_openid', $data['wx_app_openid']);
                }
                if (!empty($data['loginSession'])) {
                    $response = self::getUserIdByLoginSession($data['loginSession']);
                    if ($response->code) {
                        return self::response($response->code);
                    }
                    $user_id = $response->data;
                    $query->where('id', $user_id);
                }
            })->select(['id', 'nickname', 'mobile', 'headimgurl', 'province', 'city', 'is_init'])->get();
            if (empty($user)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $user);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getUserInfoByUserId($data)
    {
        try {
            $response = self::getPartnerIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $partner_id = $response->data;
            $user = Users::where('id', $data['user_id'])->where('partner_id', $partner_id)->select('id', 'nickname', 'headimgurl')->first();
            if (empty($user)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $user);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 获取用户列表
     * @param $data 筛选条件
     * @return mixed 返回结果
     */
    public static function getUserList($data)
    {
        try {
            $user = Users::where(function ($query) use ($data) {
                if (!empty($data['nickname'])) {
                    $query->where('nickname', 'like', '%' . $data['nickname'] . '%');
                }
                if ($data['partner_id']){
                    $query->where('partner_id', $data['partner_id']);
                }
            })->orderBy('id', 'desc')->paginate($data['limit']);
            foreach ($user as $item) {
                $partner = Partner::find($item->partner_id);
                $item->mini_progress = $partner['name'];
            }
            if (empty($user)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $user);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 给用户设置角色
     * @param $data 用户信息
     * @return mixed 返回结果
     */
    public static function setUserRole($data)
    {
        try {
            // 创建事务,给用户分配角色的一系列操作并且更新用户角色
            DB::transaction(function () use ($data) {
                // 删除之前的用户角色
                $user_mapping_role = UserMappingRole::where('user_id', $data['id'])->get();
                foreach ($user_mapping_role as $item){
                    if (!$item->delete()){
                        return self::response(self::OBJECT_DELETE_FAILD);
                    }
                }

                // 将数组字符串转化为数组
                $role_list_arr = explode(',', $data['role_list']);

                if (!empty($role_list_arr[0])) {
                    foreach ($role_list_arr as $role) {
                        // 更新用户的角色
                        $user_mapping_role = new UserMappingRole();
                        $user_mapping_role->user_id = $data['id'];
                        $user_mapping_role->role_id = $role;
                        $user_mapping_role->is_root = UserMappingRole::ROOT_MANAGERE;
                        if (!$user_mapping_role->save()) {
                            return self::response(self::OBJECT_SAVE_FAIL);
                        }
                    }
                }
            });
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 给用户设置角色
     * @param $data 用户信息
     * @return mixed 返回结果
     */
    public static function getUserRoleList($data)
    {
        try {
            $user_mapping_user = UserMappingRole::where('user_id', ($data['user_id']))->get();

            $role_list_arr = [];
            foreach ($user_mapping_user as $item) {
                array_push($role_list_arr, $item->role_id);
            }
            $role_list_string = implode(',', $role_list_arr);
            return self::response(self::SUCCESS, $role_list_string);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getYiiccaMenu($data)
    {
        try {
            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $user_id = $response->data;

            // 通过user_id获取到该用户的角色列表
            $user_mapping_role = UserMappingRole::where('user_id', $user_id)->get();

            // 判断角色是否为空，为空则为一间咖啡馆普通用户，否则为一间咖啡馆角色用户
            if ($user_mapping_role->isEmpty()) {
                $yiicca_common_menu = Menu::where('type', Menu::YIICCA_COMMON_MENU)->where('status', 1)->get();
                $menu[0] = new Collection(['id' => 0, 'name' => Menu::$progressArray[Menu::YIICCA_COMMON_MENU], 'menu' => $yiicca_common_menu->toArray()]);

            } else {
                // 获取角色用户的菜单
                $role = Role::with(['menu'])->whereHas('user', function ($query) use ($user_id){
                    $query->where('users.id', $user_id);
                })->whereHas('menu', function ($query){
                    $query->where('status', 1);
                })->select('id', 'name')->get()->groupBy('role_id');
                if (empty($role)) {
                    return self::response(self::CONTENT_IS_EMPTY);
                }

                // 获取一间咖啡馆的普通用户菜单
                $yiicca_common_menu = Menu::where('type', Menu::YIICCA_COMMON_MENU)->where('status', 1)->get();
                if (empty($yiicca_common_menu)) {
                    return self::response(self::CONTENT_IS_EMPTY);
                }

                // 获取到角色菜单数组
                $role_arr = $role->toArray()[''];

                // 将普通用户的菜单数组追加到角色用户的菜单数组中
                array_unshift($role_arr, ['id' => 0, 'name' => Menu::$progressArray[Menu::YIICCA_COMMON_MENU], 'menu' => $yiicca_common_menu->toArray()]);

                // 将组合好的菜单数组转化为集合
                $menu = new Collection($role_arr);
            }

            return self::response(self::SUCCESS, $menu);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function createMiniProgramQrcode($data)
    {
        try {
            $response = self::getPartnerIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $partner_id = $response->data;
            $response = self::createMiniProgressQrcodeUnlimit($partner_id, $data['page'], $data['scene']);
            if ($response->code) {
                return self::response($response->code);
            }
            return self::response(self::SUCCESS, $response->data);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    /**
     * 给用户设置菜单
     * @param $data 菜单信息
     * @return mixed 返回结果
     */
    public static function setUserMenu($data)
    {
        try {
            $response = self::getUserIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $user_id = $response->data;
            $user = Users::find($user_id);
            if (empty($user)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }

            // 防止重复授权，检查是否已经是管理员
            $user_mapping_role = UserMappingRole::where('user_id', $user_id)->get();
            if ($user_mapping_role->isEmpty()) {
                return self::response(self::GET_MANAGER_AGAIN);
            }

            // 创建事务，给用户分配管理员权限
            DB::transaction(function () use ($data, $user, $user_id) {
                // 给管理员创建新的角色
                $role = new Role();
                $role->name = $user->nickname;
                $role->type = Role::CAFE_MINI_PROGRAM_MANAGER;
                if (!$role->save()) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }
                $role_id = $role->id;

                // 将角色和用户关联起来
                $user_mapping_role = new UserMappingRole();
                $user_mapping_role->user_id = $user_id;
                $user_mapping_role->role_id = $role_id;
                if (!$user_mapping_role->save()) {
                    return self::response(self::OBJECT_SAVE_FAIL);
                }

                $role_data = [
                    'role_id' => $role_id,
                    'menu_list' => $data['menu_id_str']
                ];

                // 给角色分配菜单
                $response = RoleLogic::setRoleMenu($role_data);
                if ($response->code) {
                    return self::response($response->code);
                }
            });
            return self::response(self::SUCCESS);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getAssistantList($data)
    {
        try {
            $response = self::getPartnerIdByLoginSession($data['loginSession']);
            if ($response->code) {
                return self::response($response->code);
            }
            $partner_id = $response->data;

            // 找到超级管理员的角色ID
            $partner = Partner::find($partner_id);
            if (empty($partner)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $role_id = $partner->role_id;

            // 为了不返还超级管理员，找到超级管理员的用户ID，将其过滤掉
            $user_mapping_role = UserMappingRole::where('role_id', $role_id)->first();
            if (empty($partner)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $user_id = $user_mapping_role->user_id;

            $user = Users::join('user_mapping_role', 'users.id', '=', 'user_mapping_role.user_id')->where('users.id', '!=', $user_id)->where('partner_id', $partner_id)->select('users.id', 'users.nickname', 'users.headimgurl', 'users.mobile')->get();
            if (empty($user)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            foreach ($user as $item) {
                $user_mapping_role = UserMappingRole::where('user_id', $item->id)->first();
                $role = Role::find($user_mapping_role->role_id);
                $item->role_name = $role->name;
            }
            if (empty($user)) {
                return self::response(self::CONTENT_IS_EMPTY);
            }
            return self::response(self::SUCCESS, $user);
        }catch (\Exception $e){
            return self::response(self::SYSTEM_ERROR);
        }
    }

    public static function getCashCoupon($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $cash_coupon = CashCoupon::find($data['cash_coupon_id']);
        if (empty($cash_coupon)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        // 判断代金券是否领取完
        if ($cash_coupon->num === 0){
            return self::response(self::CASH_COUPON_IS_EMPTY);
        }

        // 防止用户重复领取代金券
        $user_mapping_cash_coupon = UserMappingCashCoupon::where('user_id', $user_id)->where('cash_coupon_id', $data['cash_coupon_id'])->first();
        if (!empty($user_mapping_cash_coupon)){
            return self::response(self::GET_CASH_COUPON_AGAIN);
        }

        $user_mapping_cash_coupon = new UserMappingCashCoupon();
        $user_mapping_cash_coupon->user_id = $user_id;
        $user_mapping_cash_coupon->cash_coupon_id = $data['cash_coupon_id'];
        // 为该小程序生成key，并且防止重复
        $flag = true;
        while ($flag){
            $code = randomStr(14);
            $user_mapping_cash_coupon_two = UserMappingCashCoupon::where('code', $code)->first();
            if (empty($user_mapping_cash_coupon_two)){
                $flag = false;
            }
        }
        $user_mapping_cash_coupon->code = $code;
        if (!$user_mapping_cash_coupon->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }

        // 代金券总数减一
        $cash_coupon->num -=1;
        if (!$cash_coupon->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }

        return self::response(self::SUCCESS);
    }

    public static function getUserCashCouponList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $cash_coupon_id_arr = UserMappingCashCoupon::where('user_id', $user_id)->select('cash_coupon_id')->get();
        if (empty($cash_coupon_id_arr)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $cash_coupon = CashCoupon::whereIn('id', $cash_coupon_id_arr)->orderBy('id', 'desc')->get();
        if (empty($cash_coupon)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        foreach ($cash_coupon as $item){
            $user_mapping_cash_coupon = UserMappingCashCoupon::where('cash_coupon_id', $item->id)->first();
            if (empty($user_mapping_cash_coupon)){
                return self::response(self::CONTENT_IS_EMPTY);
            }
            $item->is_used = $user_mapping_cash_coupon->is_used;
        }

        return self::response(self::SUCCESS, $cash_coupon);
    }

    public static function getUserPartyList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $party_id_arr = PartySignUp::where('user_id', $user_id)->select('party_id')->get();

        if (empty($party_id_arr)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $party = Party::whereIn('id', $party_id_arr)->get();
        if (empty($party)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        return self::response(self::SUCCESS, $party);
    }

    /**
     * 获取用户关注的咖啡馆列表
     * @param $data
     * @return mixed
     */
    public static function getFollowedCafeList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $query = Cafe::whereHas('followedUser', function ($query) use ($user_id) {
            $query->where('users.id', $user_id);
        })->orderBy('id', 'desc');

        $cafe = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $cafe_second = $data['limit'] ? $cafe->items() : $cafe;
        foreach ($cafe_second as $item){
            $item->is_followed = UserFollowCafe::FOLLOWED;
        }

        return self::response(self::SUCCESS, $cafe);
    }

    /**
     * 获取用户关注标签列表
     * @param $data
     * @return mixed
     */
    public static function getFollowedMarkList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $query = Mark::whereHas('followedUser', function ($query) use ($user_id){
            $query->where('users.id', $user_id);
        })->orderBy('id', 'desc');

        $mark = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($mark)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $mark_second = $data['limit'] ? $mark->items() : $mark;
        foreach ($mark_second as $item){
            $item->is_followed = UserFollowCafe::FOLLOWED;
        }

        return self::response(self::SUCCESS, $mark);
    }


    /**
     * 获取分享的咖啡馆列表
     * @param $data
     * @return mixed
     */
    public static function getSharedCafeList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $cafe = Cafe::whereHas('user', function ($query) use ($user_id){
            $query->where('users.id', $user_id);
        })->orderBy('id', 'desc')->get();

        if (empty($cafe)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        return self::response(self::SUCCESS, $cafe);
    }

    /**
     * 获取用户关注的城市列表
     * @param $data
     * @return mixed
     */
    public static function getFollowedCityList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $query = City::whereHas('followedUser', function ($query) use ($user_id){
           $query->where('users.id', $user_id);
        });
        $city = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($city)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $city_second = $data['limit'] ? $city->items() : $city;
        foreach ($city_second as $item){
            $item->is_followed = UserFollowCafe::FOLLOWED;
        }

        return self::response(self::SUCCESS, $city);
    }

    /**
     * 设置用户已经初始化
     * @param $data
     * @return mixed
     */
    public static function setUserInit($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $user = Users::find($user_id);
        if (empty($user)){
            return self::response(self::CONTENT_IS_EMPTY);
        }

        $user->is_init = 1;
        if (!$user->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }

        return self::response(self::SUCCESS);
    }

    public static function createUserFormId($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $user_form_id = new UserFormId();
        $user_form_id->user_id = $user_id;
        $user_form_id->form_id = $data['form_id'];
        $user_form_id->expired_at = Carbon::now()->addDays(7);
        if (!$user_form_id->save()){
            return self::response(self::OBJECT_SAVE_FAIL);
        }
        return self::response(self::SUCCESS);
    }

    /**
     * 获取用户管理的城市列表
     * @param $data
     * @return mixed
     */
    public static function getManageCityList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code){
            return self::response($response->code);
        }
        $user_id = $response->data;

        $city = City::whereHas('user', function ($query) use ($user_id){
            $query->where('user_id', $user_id);
        })->get();
        if (empty($city)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $city);
    }

    /**
     * 获取每一天的用户数据
     * @param $data
     * @return mixed
     */
    public static function getUserByDay($data)
    {
        $user = Users::where('created_at','>',strtotime($data['start_date']))
            ->where('created_at','<',strtotime($data['end_date'] + '1 Day'))
            ->groupBy('day')
            ->get([DB::raw('FROM_UNIXTIME(created_at,\'%Y-%m-%d\') as day'), DB::raw('COUNT(*) as value')]);
        if (empty($user)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $user);
    }

    /**
     * 用户点赞动态
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    public static function praiseDynamic($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        $user_praise_dynamic = UserPraiseDynamic::where('user_id', $user_id)->where('dynamic_id', $data['dynamic_id'])->first();
        if (!empty($user_praise_dynamic)){
            if (!$user_praise_dynamic->delete()){
                return self::response(self::OBJECT_DELETE_FAILD);
            }
            return self::response(self::SUCCESS, 0);
        }
        $user_praise_dynamic = new UserPraiseDynamic();
        $user_praise_dynamic->dynamic_id = $data['dynamic_id'];
        $user_praise_dynamic->user_id = $user_id;
        if (!$user_praise_dynamic->save()) {
            return self::response(self::USER_PRAISE_DYNAMIC_FAILD);
        }
        return self::response(self::SUCCESS, 1);
    }

    public static function getPraiseDynamicList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;
        $query = Dynamic::with(['dynamicVideo', 'dynamicPhoto','user'])->whereHas('userPraiseDynamic', function ($query) use ($user_id){
            $query->where('user_praise_dynamic.user_id', $user_id);
        })->orderBy('created_at', 'desc');
        $dynamic = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($dynamic)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $dynamic);
    }

    public static function getDynamicCommentList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;
        $query = DynamicComment::with(['dynamic', 'reUser'])->where('user_id', $user_id)->orderBy('created_at', 'desc');
        $dynamic_comment = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($dynamic_comment)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $dynamic_comment);
    }

    public static function getPraiseList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        // 把所有的赞设置为已读
        UserPraiseDynamic::whereHas('dynamic', function ($query) use ($user_id){
                $query->where('dynamic.user_id', $user_id);
            })
            // 过滤掉自己对自己的赞
            ->where('user_id', '!=', $user_id)->update(['is_read' => 1]);

        $query = UserPraiseDynamic::with(['dynamic' => function($query) use ($user_id){
            $query->with(['dynamicVideo', 'dynamicPhoto'])->where('dynamic.user_id', $user_id);
        }, 'user'])
            ->whereHas('dynamic', function ($query) use ($user_id){
                $query->where('dynamic.user_id', $user_id);
            })
            // 过滤掉自己对自己的赞
            ->where('user_id', '!=', $user_id)
            ->orderBy('id', 'desc');
        $user_praise_dynamic = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($user_praise_dynamic)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $user_praise_dynamic);
    }

    public static function getCommentList($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        DynamicComment::where('re_user_id', $user_id)->update(['is_read' => 1]);

        $query = DynamicComment::with(['dynamic', 'dynamic.dynamicVideo', 'dynamic.dynamicPhoto', 'user'])->where('re_user_id', $user_id)->orderBy('id', 'desc');
        $dynamic_comment = $data['limit'] ? $query->paginate($data['limit']) : $query->get();
        if (empty($dynamic_comment)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $dynamic_comment);
    }

    public static function getUnreadPraiseCount($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        $unread_count = UserPraiseDynamic::whereHas('dynamic', function($query) use ($user_id){
            $query->where('dynamic.user_id', $user_id);
        })
            // 过滤掉自己对自己的赞
            ->where(function ($query) use ($user_id){
                $query->where('user_id', '!=', $user_id);
                $query->where('is_read', 0);
            })->count();
        return self::response(self::SUCCESS, $unread_count);
    }

    public static function getUnreadCommentCount($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;
        $unread_count = DynamicComment::where(function($query) use ($user_id){
            $query->where('re_user_id', $user_id);
            $query->where('is_read', 0);
        })->count();
        return self::response(self::SUCCESS, $unread_count);
    }

    public static function getUnreadSystemNotifyCount($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;

        // 获取未读的别人评论的数量
        $unread_count1 = DynamicComment::where(function($query) use ($user_id){
            $query->where('re_user_id', $user_id);
            $query->where('is_read', 0);
        })->count();

        // 获取未读的别人给的赞的数量
        $unread_count2 = UserPraiseDynamic::whereHas('dynamic', function($query) use ($user_id){
            $query->where('dynamic.user_id', $user_id);
        })
            // 过滤掉自己对自己的赞
            ->where(function ($query) use ($user_id){
                $query->where('user_id', '!=', $user_id);
                $query->where('is_read', 0);
            })->count();

        $unread_count = $unread_count1 + $unread_count2;

        return self::response(self::SUCCESS, $unread_count);
    }

    public static function getUserDetail($data)
    {
        $response = self::getUserIdByLoginSession($data['loginSession']);
        if ($response->code) {
            return self::response($response->code);
        }
        $user_id = $response->data;
        $user = Users::with(['city', 'cafe', 'partner', 'adminMenu'])->find($user_id);
        if (empty($user)){
            return self::response(self::CONTENT_IS_EMPTY);
        }
        return self::response(self::SUCCESS, $user);
    }
}